package com.syqc.monitor.ui.historyline

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.util.LruCache
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.text.HtmlCompat
import androidx.core.view.isInvisible
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.BitmapDescriptor
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.model.PolylineOptions
import com.syqc.maps.utils.MapUtil
import com.syqc.adapter.StopLineAdapter
import com.syqc.comlib.custom.MLoadingDialog
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.Language
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.startActivityTo
import com.syqc.entity.HistoryLine
import com.syqc.maps.utils.NaviActivity
import com.syqc.maps.utils.StopMarker
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentStopLineBinding
import com.syqc.monitor.popup.StopPopup
import com.syqc.utils.DataUtil
import com.syqc.utils.Keys
import com.syqc.videos.StopVideoActivity

/**
 *@Author Jasper
 *@Time   2020/8/12
 *@Desc   历史轨迹--停车
 */
class StopLineFragment(
    private val carName: String,
    private val carId: String,
    private val video: String?
) : Fragment() {
    private var index = 0
    private var length = 0
    private val mAllPoints = ArrayList<LatLng>()
    private val dataAdapter by lazy { StopLineAdapter(video) }
    private lateinit var binding: FragmentStopLineBinding
    private lateinit var mMapA: AMap
    private val stopData by lazy { DataUtil.HistoryLine?.stopData }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        binding = FragmentStopLineBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        MapsInitializer.updatePrivacyShow(requireContext(), true, true)
        MapsInitializer.updatePrivacyAgree(requireContext(), true)
        binding.mMapView.onCreate(savedInstanceState)
        mMapA = binding.mMapView.map
        MapUtil.initMapSetting(mMapA, false)

    }

    //空布局
    private val emptyView by lazy {
        val view = layoutInflater.inflate(
            R.layout.layout_empty_view,
            binding.viewPager,
            false
        )
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(requireContext(), R.mipmap.ic_empty)
        view
    }


    private fun initData() {
        if (isScroll) {
            isScroll = false
            StopPopup(requireContext()).showAtLocation(binding.root, Gravity.NO_GRAVITY, 0, 0)
        }
        binding.ivPrevious.isInvisible = true
        binding.ivNext.isInvisible = true
        binding.viewPager.adapter = dataAdapter
        if (stopData.isNullOrEmpty()) {
            dataAdapter.setEmptyView(emptyView)
            return
        }
        dataAdapter.setList(stopData)
        initLineData(DataUtil.HistoryLine!!.locations)
        length = stopData?.size ?: 0

    }

    private fun initEvent() {
        mMapA.setOnMarkerClickListener { marker ->

            setMarkerAnimaction(marker)
            return@setOnMarkerClickListener true
        }
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                if (stopData.isNullOrEmpty()) return
                index = position
                setNum()
                stopData?.get(position)?.let {
                    addMarker(it, position + 1)
                    mMapA.moveCamera(
                        CameraUpdateFactory.newLatLngZoom(
                            LatLng(
                                it.glat.toDouble(),
                                it.glng.toDouble()
                            ), 16f
                        )
                    )
                    binding.ivNext.isInvisible = index + 1 >= length
                    binding.ivPrevious.isInvisible = index <= 0
                }

            }
        })
        binding.ivNext.setOnClickListener {
            if (index < length) {
                index++
                binding.viewPager.currentItem = index
            }
            binding.ivNext.isInvisible = index + 1 >= length
        }
        binding.ivPrevious.setOnClickListener {
            if (index > 0) {
                index--
                binding.viewPager.currentItem = index
            }
            binding.ivPrevious.isInvisible = index <= 0
        }

        //放大
        binding.ivMapZoomIn.setOnClickListener {
            mMapA.animateCamera(CameraUpdateFactory.zoomOut(), 600, null)
        }

        //缩小
        binding.ivMapZoomOut.setOnClickListener {
            mMapA.animateCamera(CameraUpdateFactory.zoomIn(), 600, null)
        }

        dataAdapter.setOnItemChildClickListener { _, view, position ->
            val stopData = dataAdapter.data[position]
            when (view.id) {
                R.id.tvStopAddr -> {

                    stopData.run {
                        startActivityTo<NaviActivity>(requireContext()) {
                            putExtra(Keys.INTENT_PLATE, carName)
                            putExtra("eLat", glat)
                            putExtra("eLng", glng)
                            putExtra("bLat", blat)
                            putExtra("bLng", blng)
                        }
                    }
                }

                R.id.ivVideo -> {
                    stopData.let {
                        startActivityTo<StopVideoActivity>(requireContext()) {
                            putExtra("startTime", it.startTime)
                            putExtra("endTime", it.endTime)
                            putExtra(Keys.INTENT_PLATE, carName)
                            putExtra(Keys.INTENT_CAR_ID, carId)
                            putExtra(Keys.VIDEO, video)
                        }
                    }
                }
            }
        }
    }

    private fun setMarkerAnimaction(marker: Marker) {
        val duration = 1000L
        val animation = com.amap.api.maps.model.animation.ScaleAnimation(1.0f, 2f, 1.0f, 2f)
        animation.setDuration(duration)
        animation.fillMode = 0
        marker.setAnimation(animation)
        marker.startAnimation()

        val animation2 = com.amap.api.maps.model.animation.ScaleAnimation(2f, 1.0f, 2f, 1.0f)
        animation2.setDuration(duration)
        animation2.fillMode = 0
        marker.setAnimation(animation2)
        marker.startAnimation()
    }

    fun setNum() {
        val htmlStr =
            "<font color='#2461f7'>${index + 1}</font><font color='#333333'> / $length</font>"
        val html = HtmlCompat.fromHtml(htmlStr, HtmlCompat.FROM_HTML_MODE_LEGACY)
        binding.tvNum.text = html
    }

    private var marker: Marker? = null

    private fun addMarker(stopData: HistoryLine.StopData, position: Int) {

        if (marker != null) {
            marker?.position = LatLng(stopData.glat.toDouble(), stopData.glng.toDouble())
            marker?.setIcon(getIcon(position))
        } else {
            marker = MapUtil.addTagMarker(
                mMapA,
                LatLng(stopData.glat.toDouble(), stopData.glng.toDouble()),
                getIcon(position),
                position
            )
        }
        setMarkerAnimaction(marker!!)

    }

    private fun getIcon(position: Int): BitmapDescriptor {
        var bitmapDescriptor = lruCache.get(position)
        if (bitmapDescriptor == null) {
            val markerView = StopMarker(requireContext(), position)
            bitmapDescriptor = BitmapDescriptorFactory.fromView(markerView)
            lruCache.put(position, bitmapDescriptor)
        }
        return bitmapDescriptor!!
    }


    /**
     * 设置轨迹 起终点
     *
     * @param lineData
     */
    private fun initLineData(lineData: List<HistoryLine.Location>) {
        val bounds = LatLngBounds.builder()
        lineData.forEach {
            val latLng = LatLng(it.glat.toDouble(), it.glng.toDouble())
            mAllPoints.add(latLng)
            bounds.include(latLng)
        }
        mMapA.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), 100))


        //画线 有需要可以参照其它画线功能添加图片
        val polylineOptions = PolylineOptions()
        polylineOptions.points = mAllPoints
        polylineOptions.width(20f).customTexture =
            BitmapDescriptorFactory.fromResource(R.mipmap.ic_line_custtexture)
        polylineOptions.isDottedLine = true

        mMapA.addPolyline(polylineOptions)

        val startPoint = mAllPoints.first()
        val endPoint = mAllPoints.last()
        //开始点
        MapUtil.addAndGetMarker(
            mMapA, startPoint,
            if (Language.isEnglish()) R.mipmap.ic_marker_start_e else R.mipmap.ic_marker_start
        ).isClickable = false
        //结束点
        MapUtil.addAndGetMarker(
            mMapA, endPoint,
            if (Language.isEnglish()) R.mipmap.ic_marker_end_e else R.mipmap.ic_marker_end
        ).isClickable = false


    }

    private var isFirstLoad = true // 是否第一次加载

    override fun onDestroyView() {
        super.onDestroyView()
        isFirstLoad = true
    }

    override fun onResume() {
        super.onResume()
        if (isFirstLoad) {
            isFirstLoad = false
            // 将数据加载逻辑放到onResume()方法中
            initData()
            initEvent()
        }
        binding.mMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.mMapView.onPause()
    }

    override fun onDestroy() {
        mMapA.clear()
        binding.mMapView.onDestroy()
//        markers.clear()
        MLoadingDialog.dismiss()
        super.onDestroy()

    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mMapView.onSaveInstanceState(outState)
    }

    ////////////////////缓存/////////////////////////////////////////////
    val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
    private var lruCache = object : LruCache<Int, BitmapDescriptor?>(maxMemory) {
        override fun entryRemoved(
            evicted: Boolean,
            key: Int,
            oldValue: BitmapDescriptor?,
            newValue: BitmapDescriptor?
        ) {
            super.entryRemoved(evicted, key, oldValue, newValue)
            oldValue?.recycle()
        }
    }

    private var isScroll
        get() = CacheMMKV.decodeBooleanSave("isScroll", true)
        set(value) = CacheMMKV.encodeSave("isScroll", value)
}
